package com.hckj.jianzhijia;

import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVUser;
import com.avos.avoscloud.LogInCallback;
import com.hckj.jianzhijia.controllers.LoginController;
import com.hckj.jianzhijia.model.City;
import com.hckj.jianzhijia.model.CompanyUser;
import com.hckj.jianzhijia.model.Province;
import com.hckj.jianzhijia.model.Region;
import com.hckj.jianzhijia.utils.ExceptionUtils;
import com.hckj.jianzhijia.utils.SharedPreferencesUtil;
import com.hckj.jianzhijia.utils.ToastUtils;
import com.rey.material.widget.CheckBox;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.InjectView;

public class LoginActivity extends BaseActivity {


    @InjectView(R.id.imgv_app_logo)
    ImageView imgvAppLogo;
    @InjectView(R.id.edt_phone_num)
    EditText edtPhoneNum;
    @InjectView(R.id.edt_password)
    EditText edtPassword;
    @InjectView(R.id.imgv_show_password)
    ImageView imgvShowPassword;
    @InjectView(R.id.ll_account_input)
    LinearLayout llAccountInput;
    @InjectView(R.id.cb_remember_password)
    CheckBox cbRememberPassword;
    @InjectView(R.id.tv_forget_password)
    TextView tvForgetPassword;
    @InjectView(R.id.btn_login)
    Button btnLogin;
    @InjectView(R.id.tv_registe_account)
    TextView tvRegisteAccount;
    @InjectView(R.id.tv_job_seeker)
    TextView tvJobSeeker;
    @InjectView(R.id.imgv_clean_account)
    ImageView imgvCleanAccount;

    private String phoneNum;
    private String password;
    private LoginController loginController;
    private boolean passwordSeen = false;
    private boolean isAutoLogin = false;
    private ProgressDialog loadingDialog;
    private SharedPreferencesUtil sharedPreferencesUtil;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.inject(this);
        sharedPreferencesUtil = new SharedPreferencesUtil(this);
        loadingDialog = new ProgressDialog(this);
        loadingDialog.setCancelable(false);
        loadingDialog.setMessage("正在登录");
        loginController = new LoginController(this);
        initData();
        initEvent();
    }

    private void initData() {
        //edtPhoneNum.setText(sharedPreferencesUtil.getCurrentUserPhone());
    }


    /**
     * 用于绑定监听
     */
    private void initEvent() {

        imgvShowPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(passwordSeen){//密码可见
                    edtPassword.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    imgvShowPassword.setImageResource(R.drawable.looked);
                    passwordSeen = false;
                }else{
                    edtPassword.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_PASSWORD);
                    imgvShowPassword.setImageResource(R.drawable.look);
                    passwordSeen = true;
                }
            }
        });
        tvForgetPassword.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(),MidifyPasswordActivity.class));
            }
        });

        tvRegisteAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(new Intent(getApplicationContext(), RegisterActivity.class));
            }
        });
        tvJobSeeker.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getApplicationContext(), WebPageActivity.class);
                intent.putExtra("WebPageType",WebPageActivity.WEBPAGE_DOWNLOAD);
                startActivity(intent);
            }
        });
        imgvCleanAccount.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                edtPhoneNum.setText("");
            }
        });
        edtPhoneNum.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 0) {
                    imgvCleanAccount.setVisibility(View.GONE);
                } else {
                    imgvCleanAccount.setVisibility(View.VISIBLE);
                }

            }
        });
        btnLogin.setOnClickListener(new OnLoginBtnClickListener());


    }

    /**
     * 用于登陆按钮的监听
     */
    class OnLoginBtnClickListener implements  View.OnClickListener{
        @Override
        public void onClick(View v) {
            getDataFromEdt();
            if(!loginController.checkAllData(phoneNum,password)){
                return;
            }else{

                LoginNetTask loginNetTask = new LoginNetTask();
                loginNetTask.execute();
            }
        }
    }

    private class LoginNetTask extends AsyncTask<Void, Void,String>{

        @Override
        protected String doInBackground(Void... params) {
            try {
                AVUser avUser = AVUser.logIn(phoneNum, password);
                if(avUser.getInt("userType")==0){
                    avUser.logOut();
                    return "您的账号为找兼职版账号，请重新注册";
                }
                avUser.getAVObject("userInfo").fetchIfNeeded();
                jianzhijiaApplacation.setCompanyUser(new CompanyUser(avUser));
                AVQuery provinceQuery = new AVQuery(Province.TABLE_NAME);
                AVQuery cityQuery = new AVQuery(City.TABLE_NAME);
                AVQuery regionQuery = new AVQuery(Region.TABLE_NAME);
                provinceQuery.whereEqualTo("provinceId", jianzhijiaApplacation.getCompanyUser().getProvinceId());
                cityQuery.whereEqualTo("cityId",jianzhijiaApplacation.getCompanyUser().getCityId());
                regionQuery.whereEqualTo("regionId", jianzhijiaApplacation.getCompanyUser().getRegionId());
                List provinceList =  provinceQuery.find();
                List cityList =  cityQuery.find();
                List regionList =  regionQuery.find();

                if(provinceList.size()!=0){
                    jianzhijiaApplacation.getCompanyUser().setProvinceName(new Province((AVObject)(provinceList.get(0))).getProvince());
                }

                if(cityList.size()!=0){
                    jianzhijiaApplacation.getCompanyUser().setCityName(new City((AVObject) (cityList.get(0))).getCity());
                }

                if(regionList.size()!=0){
                    jianzhijiaApplacation.getCompanyUser().setRegionName(new Region((AVObject) (regionList.get(0))).getRegion());
                }


                sharedPreferencesUtil.setAutoLogin(isAutoLogin);
                sharedPreferencesUtil.setCurrentUserPhonePassword(phoneNum, password);
                return null;
            } catch (AVException e) {
                e.printStackTrace();
                return ExceptionUtils.getExceptionInfo(e);
            }
        }

        @Override
        protected void onPostExecute(String aVoid) {
            if (aVoid == null) {
                loadingDialog.dismiss();
                startActivity(new Intent(getApplicationContext(), MainActivity.class));
                LoginActivity.this.finish();
                ToastUtils.showToast(getApplicationContext(), "登录成功");
            }else{
                loadingDialog.dismiss();
                ToastUtils.showToast(getApplicationContext(), aVoid);
            }
            super.onPostExecute(aVoid);
        }

        @Override
        protected void onPreExecute() {
            loadingDialog.show();
            super.onPreExecute();
        }
    }

    private void getDataFromEdt(){
        phoneNum = edtPhoneNum.getText().toString().trim();
        password = edtPassword.getText().toString().trim();
        isAutoLogin = cbRememberPassword.isChecked();
    }

}
